﻿using RantopadService.Business;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace RantopadService
{
    /// <summary>
    /// WebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://ranto.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {

        #region 用户相关
        [WebMethod(Description = "获取用户名")]
        public string getUserName(string email)
        {
            try
            {
                return UserBusiness.getUserName(email);
            }
            catch (Exception e)
            {
                //LogFile.WriteLog(DateTime.Now.ToString() + ":"+e.Message.ToString());
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="psw"></param>
        /// <returns></returns>
        [WebMethod(Description = "登录")]
        public string login(string userID, string psw)
        {
            try
            {
                psw = MD5Helper.GetMd5Str(psw);
                var r = UserBusiness.DoLogin(userID, psw);
                if (r)
                {
                    return "true";
                }

                else
                {
                    if (UserBusiness.DoLoginByEmail(userID, psw))//尝试邮箱登录
                    {
                        return "true";
                    }
                    else
                    {
                        return "false";
                    }

                }
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }


        }

        /// <summary>
        /// 用户下线
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        [WebMethod(Description = "登出")]
        public string logout(string userID)
        {
            try
            {
                var r = UserBusiness.DoLogout(userID);
                if (r > 0)
                {
                    return "true";
                }

                else
                    return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        /// <summary>
        /// 注册新用户
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="psw"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        [WebMethod(Description = "注册新用户")]
        public string addUser(string userID, string psw, string email)
        {
            try
            {
                psw = MD5Helper.GetMd5Str(psw);
                var e = UserBusiness.checkUserEmail(email);
                if (e > 0)
                    return "邮箱已存在";
                e = UserBusiness.checkUserId(userID);
                if (e > 0)
                    return "用户名已存在";
                var r = UserBusiness.addUser(email, userID, psw);
                if (r > 0)
                    return "true";
                else
                    return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        /// <summary>
        /// 更改密码
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="psw"></param>
        /// <param name="newpsw"></param>
        /// <returns></returns>
        [WebMethod(Description = "修改密码")]
        public string changePsw(string userID, string psw, string newpsw)
        {
            try
            {
                psw = MD5Helper.GetMd5Str(psw);
                newpsw = MD5Helper.GetMd5Str(newpsw);
                var r = UserBusiness.ChangePSW(userID, psw, newpsw);
                if (r)
                    return "true";
                else
                    return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        #endregion

        #region 配置相关
        /// <summary>
        /// 接收上传配置,并返回配置ID
        /// </summary>
        /// <param name="devId">设备ID</param>
        /// <param name="name">配置名称</param>
        /// <param name="userId">用户名</param>
        /// <param name="refrese">灵敏度</param>
        /// <param name="sensibility">刷新率</param>
        /// <param name="keySetting">按键设置</param>
        /// <param name="keyLight">按键灯</param>
        /// <param name="time">配置添加或更改时间</param>
        /// <param name="optionhash">哈希值</param>
        /// <returns></returns>
        [WebMethod(Description = "添加配置,并返回配置ID")]
        public string addOption(string devId, string name, string userId, string refrese, string sensibility, DataTable keySetting, DataTable keyLight, DateTime time, string optionhash)
        {
            try
            {
                var result = OptionBusiness.addNewOption(devId, name, userId, refrese, sensibility, keySetting, keyLight, time, optionhash);
                return result;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        /// <summary>
        /// 更新配置
        /// </summary>
        /// <param name="id">配置ID</param>
        /// <param name="devId">设备ID</param>
        /// <param name="name">配置名称</param>
        /// <param name="userId">用户名</param>
        /// <param name="refrese">灵敏度</param>
        /// <param name="sensibility">刷新率</param>
        /// <param name="keySetting">按键设置</param>
        /// <returns></returns>
        [WebMethod(Description = "更新配置")]
        public string updateOption(string id, string devId, string name, string userId, string refrese, string sensibility, DataTable keySetting, DataTable keyLight, DateTime time, string optionhash)
        {
            try
            {
                var r = OptionBusiness.updateOption(id, devId, name, userId, refrese, sensibility, time, optionhash);
                if (r > 0)
                {
                    OptionBusiness.delKeyLight(id);
                    OptionBusiness.delKeySetting(id);
                    OptionBusiness.addNewKeyLightOfOption(keyLight);
                    OptionBusiness.addNewKeySettingOfOption(keySetting);
                    return "true";
                }
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }

        [WebMethod(Description = "根据 string strPid，string userid获取 string optionname的集合")]
        public List<string> getOptionNameList(string strPid, string userid)
        {
            try
            {
                List<string> nameList = new List<string>();
                nameList = OptionBusiness.GetAllOptionName(strPid, userid);
                return nameList;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }

        [WebMethod(Description = "更新服务端配置")]
        public string updateOptionByVersion(string id, string devId, string name, string userId, string refrese, string sensibility, DataTable keySetting, DataTable keyLight, string optionVersion, DateTime time, string optionhash)
        {
            try
            {
                var r = OptionBusiness.updateOption(id, devId, name, userId, refrese, sensibility, optionVersion, time, optionhash);
                if (r > 0)
                {
                    OptionBusiness.delKeyLight(id);
                    OptionBusiness.delKeySetting(id);
                    OptionBusiness.addNewKeyLightOfOption(keyLight);
                    OptionBusiness.addNewKeySettingOfOption(keySetting);
                    return "true";
                }
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "顶配置")]
        public string upOption(string id)
        {
            try
            {
                var r = OptionBusiness.upOption(id, "+");
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "踩配置")]
        public string downOption(string id)
        {
            try
            {
                var r = OptionBusiness.downOption(id, "+");
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "取消顶配置")]
        public string cancelUpOption(string id)
        {
            try
            {
                var r = OptionBusiness.upOption(id, "-");
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "取消踩配置")]
        public string cancelDownOption(string id)
        {
            try
            {
                var r = OptionBusiness.downOption(id, "-");
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "分享配置")]
        public string shareOption(string id)
        {
            try
            {
                var r = OptionBusiness.shareOption(id);
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "取消分享配置")]
        public string unShareOption(string id)
        {
            try
            {
                var r = OptionBusiness.unshareOption(id);
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "分享宏")]
        public string shareMacro(string userName, string macroName, string macroContent)
        {
            var r = OptionBusiness.shareMacro(userName, macroName, macroContent);
            if (r > 0)
                return "true";
            return "false";
        }
        [WebMethod(Description = "取消分享宏")]
        public string unShareMacro(string strUserId, string strMacroName)
        {
            try
            {
                var r = OptionBusiness.unshareMacro(strUserId, strMacroName);
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }
        }
        [WebMethod(Description = "顶分享宏")]
        public string upShareMacro(string strUserId, string strMacroName)
        {
            try
            {
                var r = OptionBusiness.upShareMacro(strUserId, strMacroName, "+");
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }
        }
        [WebMethod(Description = "获取单个分享宏")]
        public DataTable getShareMacro(string strUserId, string strMaroName)
        {
            try
            {
                var r = OptionBusiness.getShareMacro(strUserId, strMaroName);
                r.TableName = "ShareMacro";
                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        [WebMethod(Description = "踩分享宏")]
        public string downShareMacro(string strUserId, string strMacroName)
        {
            try
            {
                var r = OptionBusiness.downShareMacro(strUserId, strMacroName, "+");
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "取消顶分享宏")]
        public string cancelUpShareMacro(string strUserId, string strMacroName)
        {
            try
            {
                var r = OptionBusiness.upShareMacro(strUserId, strMacroName, "-");
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "取消踩分享宏")]
        public string cancelDownShareMacro(string strUserId, string strMacroName)
        {
            try
            {
                var r = OptionBusiness.downShareMacro(strUserId, strMacroName, "-");
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        ///<summary>
        ///获取配置排行榜列表
        ///</summary>
        ///<param name="top">要获取排行榜的前top条数据</param>
        ///<returns></returns>
        [WebMethod(Description = "获取配置排行榜列表")]
        public DataTable getTopOptions(int top)
        {
            try
            {
                var r = OptionBusiness.getTopOptions(top, "");
                r.TableName = "Top" + top;
                DataColumn colno = new DataColumn("Num");
                r.Columns.Add(colno);
                for (int i = 0; i < r.Rows.Count; i++)
                {
                    r.Rows[i]["Num"] = i + 1;
                }
                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        /// <summary>
        /// 获取配置排行榜列表
        /// </summary>
        /// <param name="top">要获取排行榜的前top条数据</param>
        /// <returns></returns>
        [WebMethod(Description = "获取配置排行榜列表")]
        public DataTable getTopOptionsByName(int top, string name)
        {
            try
            {
                var r = OptionBusiness.getTopOptions(top, name);
                r.TableName = "Top" + top;
                DataColumn colno = new DataColumn("Num");
                r.Columns.Add(colno);
                for (int i = 0; i < r.Rows.Count; i++)
                {
                    r.Rows[i]["Num"] = i + 1;
                }
                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        [WebMethod(Description = "获取配置排行榜列表")]
        public DataTable getTopOptionsForPage(int location, int size, int orderpara,string wherelike)
        {
            try
            {
                var r = OptionBusiness.getTopOptions(location, size, wherelike, orderpara);
                r.TableName = "Top_" + location + "_" + size;
                DataColumn colno = new DataColumn("Num");
                r.Columns.Add(colno);
                for (int i = 0; i < r.Rows.Count; i++)
                {
                    r.Rows[i]["Num"] = i + 1 + location;
                }
                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        /// <summary>
        /// 获取配置排行榜列表
        /// </summary>
        /// <param name="top">要获取排行榜的前top条数据</param>
        /// <returns></returns>
        [WebMethod(Description = "获取宏排行榜列表")]
        public DataTable getTopMacros(int top)
        {
            try
            {
                var r = OptionBusiness.getTopMacros(top, "");
                r.TableName = "Top" + top;
                DataColumn colno = new DataColumn("Num");
                r.Columns.Add(colno);
                for (int i = 0; i < r.Rows.Count; i++)
                {
                    r.Rows[i]["Num"] = i + 1;
                }
                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        [WebMethod(Description = "获取宏排行榜列表")]
        public DataTable getTopMacrosForPage(int location, int size, int orderpara,string wherelike)
        {
            try
            {
                DataTable r = OptionBusiness.getTopMacros(location, size, wherelike, orderpara);
                r.TableName = "Top_" + location + "_" + size;
                DataColumn colno = new DataColumn("Num");
                r.Columns.Add(colno);
                for (int i = 0; i < r.Rows.Count; i++)
                {
                    r.Rows[i]["Num"] = i + 1 + location;
                }
                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        /// <summary>
        /// 获取配置排行榜列表
        /// </summary>
        /// <param name="top">要获取排行榜的前top条数据</param>
        /// <returns></returns>
        [WebMethod(Description = "获取宏排行榜列表")]
        public DataTable getTopMacrosByName(int top, string name)
        {
            try
            {
                var r = OptionBusiness.getTopMacros(top, name);
                r.TableName = "Top" + top;
                DataColumn colno = new DataColumn("Num");
                r.Columns.Add(colno);
                for (int i = 0; i < r.Rows.Count; i++)
                {
                    r.Rows[i]["Num"] = i + 1;
                }
                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        [WebMethod(Description = "删除配置")]
        public string delOption(string id)
        {
            try
            {
                var r = OptionBusiness.delOptionByID(id);
                if (r > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }



        [WebMethod(Description = "获取optionID")]
        public string GetOptionIdByPid(string strPid, string optionname, string userid)
        {
            try
            {
                string strOptionId = "";
                strOptionId = OptionBusiness.GetOptionIdByPid(strPid, optionname, userid);
                if (strOptionId == "")
                {
                    return "";
                }
                return strOptionId;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }

        //[WebMethod(Description = "更改配置名")]
        //public string UpdateOptionName(string id, string devId, string name, string userId, string refrese, string sensibility, DataTable keySetting, DataTable keyLight, DateTime time, string optionhash)
        //{
        //    var r = OptionBusiness.updateOption(id, devId, name, userId, refrese, sensibility, time, optionhash);
        //    if (r > 0)
        //    {
        //        OptionBusiness.delKeyLight(id);
        //        OptionBusiness.delKeySetting(id);
        //        OptionBusiness.addNewKeyLightOfOption(keyLight);
        //        OptionBusiness.addNewKeySettingOfOption(keySetting);
        //        return "true";
        //    }
        //    return "false";
        //}
        [WebMethod(Description = "获取所有配置")]
        public List<DataSet> getAllOption(string userID)
        {
            try
            {
                List<DataSet> optionList = new List<DataSet>();

                var dt = OptionBusiness.getOptionByUserID(userID);
                dt.TableName = "OPTION";
                //ds.Tables.Add(dt1);
                int i = 0;
                foreach (DataRow row in dt.Rows)
                {
                    i++;
                    DataSet ds = new DataSet();
                    DataTable dt1 = dt.Clone();
                    DataRow newrow = dt1.NewRow();
                    newrow.ItemArray = row.ItemArray;
                    dt1.Rows.Add(newrow);
                    DataTable dt2 = KeySettingBusiness.getAllKeySettingsByID(row["ID"].ToString());
                    dt2.TableName = "KEYSETTING";
                    DataTable dt3 = OptionBusiness.getAllKeyLightByID(row["ID"].ToString());
                    dt3.TableName = "KEYLIGHT";
                    ds.Tables.Add(dt1);
                    ds.Tables.Add(dt2);
                    ds.Tables.Add(dt3);

                    optionList.Add(ds);
                }

                return optionList;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        [WebMethod(Description = "下载所有宏")]
        public DataSet getAllMacro(string userId)
        {
            try
            {
                DataTable dt3 = KeySettingBusiness.getMACRO(userId);
                dt3.TableName = "MECROS";

                return XMLHelper.decodeMacroXmltoDS(dt3.Rows[0]["CONTENT"].ToString());
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        [WebMethod(Description = "下载宏")]
        public DataSet getMacro(string userId)
        {
            try
            {
                DataTable dt3 = KeySettingBusiness.getMACRO(userId);
                dt3.TableName = "MECRO";
                return XMLHelper.decodeMacroXmltoDS(dt3.Rows[0]["CONTENT"].ToString());
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }
        }

        [WebMethod(Description = "下载所有宏")]
        public DataSet getAllRawMacro(string userId)
        {
            try
            {
                DataSet ds = new DataSet();
                DataTable dt3 = KeySettingBusiness.getMACRO(userId);
                dt3.TableName = "MECROS";

                ds.Tables.Add(dt3);
                return ds;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        [WebMethod(Description = "下载宏")]
        public DataSet getRawMacro(string userId)
        {
            try
            {
                DataSet ds = new DataSet();
                DataTable dt3 = KeySettingBusiness.getMACRO(userId);
                dt3.TableName = "MECRO";
                ds.Tables.Add(dt3);

                return ds;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }

        [WebMethod(Description = "更新宏")]
        public string updateMacro(string userId, string content, DateTime time, string hash)
        {
            try
            {
                int result = KeySettingBusiness.updateMacro(userId, content, time, hash);
                if (result > 0)
                {
                    return "true";
                }
                else
                {
                    return "false";
                }
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "增加宏")]
        public string addMacro(string userId, string content, string hash)
        {
            try
            {
                int result = KeySettingBusiness.addMacro(userId, content, hash);
                if (result > 0)
                {
                    return "true";
                }
                else
                {
                    return "false";
                }
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "删除宏")]
        public string deleteMacro(string userId, string name)
        {
            try
            {
                int result = KeySettingBusiness.delMacro(userId, name);
                if (result > 0)
                {
                    return "true";
                }
                else
                {
                    return "false";
                }
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "下载配置")]
        public DataSet getOption(string id)
        {
            try
            {
                DataSet ds = new DataSet();

                var dt1 = OptionBusiness.getOptionTByID(id);
                dt1.TableName = "OPTION";


                DataTable dt2 = KeySettingBusiness.getAllKeySettingsByID(id);
                dt2.TableName = "KEYSETTING";

                DataTable dt3 = OptionBusiness.getAllKeyLightByID(id);
                dt2.TableName = "KEYLIGHT";




                ds.Tables.Add(dt1);
                ds.Tables.Add(dt2);
                ds.Tables.Add(dt3);

                return ds;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        [WebMethod(Description = "下载最新版本配置")]
        public DataSet getNewOption(string id, string optionVersion)
        {
            try
            {
                DataSet ds = new DataSet();
                var dt1 = OptionBusiness.getOptionTByID(id, optionVersion);
                dt1.TableName = "OPTION";
                if (dt1.Rows.Count == 0)
                    return ds;

                DataTable dt2 = KeySettingBusiness.getAllKeySettingsByID(id);
                dt2.TableName = "KEYSETTING";

                string userId = "";
                if (dt1.Rows.Count > 0)
                    userId = dt1.Rows[0]["USER_ID"].ToString();



                DataTable dt3 = KeySettingBusiness.getMACRO(userId);
                dt3.TableName = "MECRO";

                ds.Tables.Add(dt1);
                ds.Tables.Add(dt2);
                if (dt3.Rows.Count > 0)
                    ds.Tables.Add(dt3);
                return ds;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }


        }

        [WebMethod(Description = "评论配置")]
        public string commentOption(string id, string userID, string commentText)
        {
            try
            {
                if (CommentBusiness.addComment(id, userID, commentText) > 0)
                    return "true";
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }

        [WebMethod(Description = "获取配置评论")]
        public DataTable getcomment(string id)
        {
            try
            {
                DataTable dt = CommentBusiness.getAllCommentsByOptionID(id);

                return dt;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }


        }
        #endregion

        #region 又增加的表
        [WebMethod(Description = "增加RawCfgFile")]
        public int addRawCfgFileContent(string strUserId, string strPid, string strRawCfgFileContent, string strHash)
        {

            try
            {
                int r = RawCfgFileBusiness.addRawcfgfile(strUserId, strPid, strRawCfgFileContent, strHash);
                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return 0;
                throw;
            }
        }


        [WebMethod(Description = "更新RawCfgFile")]
        public int updateRawCfgFileContent(string strUserId, string strPid, string strRawCfgFileContent, string strHash)
        {

            try
            {
                int r = RawCfgFileBusiness.updateRawcfgfile(strUserId, strPid, strRawCfgFileContent, strHash);
                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return 0;
                throw;
            }
        }
        [WebMethod(Description = "获取RawCfgFile内容")]
        public DataTable getRawCfgFileContent(string strUserId, string strPid, ref string strRawFileContent)
        {

            try
            {
                DataTable r = RawCfgFileBusiness.getRawcfgfile(strUserId, strPid);
                r.TableName = "RawCfgFileContent";
                if (r.Rows.Count > 0)
                {
                    strRawFileContent = r.Rows[0]["cfgfilecontent"].ToString();
                }

                return r;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
                throw;
            }
        }

        [WebMethod(Description = "获取RawCfgFile信息")]
        public DataTable getRawCfgFileInfo(string strUserId, string strPid, ref DateTime lastUpdateTime, ref string strHash)
        {
            try
            {
                DataTable r = RawCfgFileBusiness.getRawcfgfile(strUserId, strPid);

                if (r.Rows.Count > 0)
                {
                    lastUpdateTime = Convert.ToDateTime(r.Rows[0]["lastUpdateTime"]);
                    strHash = r.Rows[0]["hash"].ToString();
                }

                return r;
            }
            catch (Exception)
            {
                return null;
                throw;
            }
        }
        [WebMethod(Description = "检查RawCfgFile是否存在")]
        public bool chkRawCfgFileExsited(string strUserId, string strPid)
        {
            try
            {
                int r = RawCfgFileBusiness.checkData(strUserId, strPid);
                if (r > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
                throw;
            }
        }
        #endregion


        #region 推送相关

        /// <summary>
        /// 推送消息
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        [WebMethod(Description = "推送消息")]
        public DataTable getMessage(string userID)
        {
            try
            {
                DataTable dt = new DataTable();
                //dt.Columns.Add(new DataColumn("HaveImage"));
                dt.Columns.Add(new DataColumn("Msg"));
                dt.Columns.Add(new DataColumn("ID"));
                dt.TableName = "推送消息";
                var msgTable = MessageBusiness.getMsgByUserID(userID);

                for (int i = 0; i < msgTable.Rows.Count; i++)
                {
                    var row = dt.NewRow();
                    row["Msg"] = msgTable.Rows[i]["CONTENT"].ToString();
                    row["ID"] = msgTable.Rows[i]["ID"].ToString();

                    dt.Rows.Add(row);
                }
                return dt;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }
        /// <summary>
        /// 根据消息id获取消息中的图片
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [WebMethod(Description = "推送图片")]
        public byte[] getMsgImage(string ID)
        {
            try
            {
                return MessageBusiness.getMsgImageByID(ID);

            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }
        }
        /// <summary>
        /// 更新消息发送状态为已发送2
        /// </summary>
        /// <param name="ID"></param>
        [WebMethod(Description = "更新消息发送状态为已发送")]
        public string updateMsgSendStatu(string ID)
        {
            try
            {
                if (MessageBusiness.updateMessageStatus(ID) > 0)
                {
                    return "true";
                }
                else
                {
                    return "false";
                }
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }
        [WebMethod(Description = "获取最新客户端信息")]
        public DataTable getNewClientInfo(string clientType)
        {
            DataTable dt = ClientBusiness.getNewClient(clientType);
            dt.TableName = "NewClientInfo";
            return dt;
        }
        [WebMethod(Description = "获取最新驱动信息")]
        public DataTable getNewDriverInfo(string device)
        {
            DataTable dt = DriverBusiness.getNewDriver(device);
            dt.TableName = "NewDriverInfo";
            return dt;
        }
        /// <summary>
        /// 推送客户端更新
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="clientType">客户端类型</param>
        /// <param name="clientV">用户本地客户端版本</param>
        /// <param name="Offset">偏移量（已下载的文件长度）</param>
        /// <param name="Count">每次下载的数据长度</param>
        /// <returns></returns>
        [WebMethod(Description = "推送客户端更新")]
        public byte[] getNewClient(string userID, string clientType, string clientV, long Offset, int Count)
        {
            try
            {
                DataTable dt = ClientBusiness.getNewClient(clientType);
                string newClientV = dt.Rows[0]["V"].ToString();
                string clientURI = dt.Rows[0]["URI"].ToString();
                if (clientV == newClientV)
                    return null;

                byte[] btBuf = new byte[Count];

                if (System.IO.File.Exists(clientURI))
                {
                    System.IO.FileStream fs = new System.IO.FileStream(clientURI, System.IO.FileMode.Open);
                    if (Offset < fs.Length)
                    {
                        if (0 < (int)(fs.Length - Offset) && (int)(fs.Length - Offset) < Count)
                        {
                            Count = (int)(fs.Length - Offset);
                        }
                        btBuf = new byte[Count];

                        fs.Seek(Offset, System.IO.SeekOrigin.Begin);
                        fs.Read(btBuf, 0, Count);
                    }
                    else
                    { btBuf = null; }
                    fs.Flush();
                    fs.Close();
                    fs.Dispose();
                }

                return btBuf;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }


        }

        /// <summary>
        /// 推送驱动更新
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="device">设备</param>
        /// <param name="deviceV">用户本地驱动版本</param>
        /// <param name="Offset">偏移量（已下载的文件长度）</param>
        /// <param name="Count">每次下载的数据长度</param>
        /// <returns></returns>
        [WebMethod(Description = "推送驱动更新")]
        public byte[] getNewDriver(string userID, string device, string deviceV, long Offset, int Count)
        {
            try
            {
                DataTable dt = DriverBusiness.getNewDriver(device);
                string newDriverV = dt.Rows[0]["V"].ToString();
                string driverURI = dt.Rows[0]["URI"].ToString();
                if (deviceV == newDriverV)
                    return null;

                byte[] btBuf = new byte[Count];

                if (System.IO.File.Exists(driverURI))
                {
                    System.IO.FileStream fs = new System.IO.FileStream(driverURI, System.IO.FileMode.Open);
                    if (Offset < fs.Length)
                    {
                        if (0 < (int)(fs.Length - Offset) && (int)(fs.Length - Offset) < Count)
                        {
                            Count = (int)(fs.Length - Offset);
                        }
                        btBuf = new byte[Count];

                        fs.Seek(Offset, System.IO.SeekOrigin.Begin);
                        fs.Read(btBuf, 0, Count);
                    }
                    else
                    { btBuf = null; }
                    fs.Flush();
                    fs.Close();
                    fs.Dispose();
                }
                return btBuf;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }


        }
        /// <summary>
        /// 轮询方法
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="deviceDT">设备列表</param>
        /// <param name="clientV">客户端版本</param>
        /// <returns>参数</returns>
        /// DataTable deviceDT,两列“设备型号device”“设备驱动版本driver”
        /// 返回值：datatable 三列：“客户端是否需更新Client”“驱动是否需要更新Driver”“是否有推送消息Message”
        [WebMethod(Description = "轮询方法")]//
        public DataTable pollingMethod(string userID, DataTable deviceDT, string clientV)
        {
            try
            {
                DataTable dt = new DataTable();
                dt.TableName = "pollingMethod";
                dt.Columns.Add(new DataColumn("Client"));
                dt.Columns.Add(new DataColumn("Driver"));
                dt.Columns.Add(new DataColumn("Message"));
                DataRow row = dt.NewRow();
                row[0] = "false";
                row[1] = "false";
                row[2] = "false";

                row[0] = checkClientV(clientV);
                row[1] = checkDriverV(deviceDT);
                row[2] = checkMessage(userID);

                dt.Rows.Add(row);
                return dt;
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return null;
            }

        }

        private string checkMessage(string userID)
        {
            try
            {
                var msgTable = MessageBusiness.getMsgByUserID(userID);
                if (msgTable.Rows.Count > 0)
                    return "true";
                else
                    return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }

        private string checkDriverV(DataTable deviceDT)
        {
            try
            {
                for (int i = 0; i < deviceDT.Rows.Count; i++)
                {
                    DataTable dt = DriverBusiness.getNewDriver(deviceDT.Rows[i]["device"].ToString());
                    string newDriverV = dt.Rows[0]["V"].ToString();

                    if (deviceDT.Rows[i]["driver"].ToString() != newDriverV)
                        return "true";
                }
                return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }


        }

        private string checkClientV(string clientV)
        {
            try
            {
                DataTable dt = ClientBusiness.getNewClient("1");
                string newClientV = dt.Rows[0]["V"].ToString();
                if (clientV != newClientV)
                    return "true";
                else
                    return "false";
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }

        }

        #endregion

        #region 错误日志
        [WebMethod(Description = "写错误日志")]
        public string addErrInfo(string userID, DateTime tm, string errmsg)
        {
            int result = 0;
            try
            {
                result = ErrBusiness.addErr(userID, tm, errmsg);
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }
            if (result > 0)
            {
                return "true";
            }
            return "false";
        }
        [WebMethod(Description = "获取错误日志")]
        public DataTable getErrInfo(string userID, DateTime st, DateTime et)
        {
            DataTable dt = null;
            dt = ErrBusiness.getAllErr(userID, st, et);
            return dt;
        }

        #endregion
        #region 用户反馈
        [WebMethod(Description = "写用户反馈")]
        public string addFeedBack(string userID, DateTime tm, string title,string type,string content)
        {
            int result = 0;
            try
            {
                result = FeedBackBusiness.addFeedBack(userID,title,type,content, tm);
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                return "false";
            }
            if (result > 0)
            {
                return "true";
            }
            return "false";
        }
        [WebMethod(Description = "获取用户反馈")]
        public DataTable getFeedBack(string userID, DateTime st, DateTime et)
        {
            DataTable dt = null;
            dt = FeedBackBusiness.getAllFeedBack(userID, st, et);
            return dt;
        }
        #endregion
    }
}
